<template>
  <view class="container">
    <!-- 白色极简背景 -->
    <view class="bg-gradient"></view>
    <!-- 右上角摄像头预览 -->
    <view class="camera-preview">
      <camera
        ref="cameraRef"
        device-position="front"
        resolution="high"
        output-dimension="1080p"
        flash="off"
        style="width: 120px; height: 160px; border-radius: 16px; box-shadow: 0 4px 16px rgba(0,0,0,0.08); border: 2px solid #e5e7eb;"
      />
    </view>

    <view class="interview-content">
      <!-- 面试前注意事项 -->
      <view v-if="!interviewing" class="interview-notice">
        <text class="notice-title">面试注意事项</text>
        <view class="notice-item">
          <i class="iconfont icon-tip"></i>
          <text>请确保网络连接稳定</text>
        </view>
        <view class="notice-item">
          <i class="iconfont icon-tip"></i>
          <text>找一个安静的环境进行面试</text>
        </view>
        <view class="notice-item">
          <i class="iconfont icon-tip"></i>
          <text>准备10-15分钟不被打扰的时间</text>
        </view>
        <view class="notice-item">
          <i class="iconfont icon-tip"></i>
          <text>确保设备麦克风和摄像头正常工作</text>
        </view>
      </view>

      <!-- 题目居中显示 -->
      <view v-else class="question-title-center">
        <text class="question-text animate-pop">{{ currentQuestion.text }}</text>
      </view>

      <!-- 音频进度条（自动播放，无需按钮） -->
      <view v-if="audioPlaying" class="audio-progress-bar">
        <view class="audio-bar">
          <view class="audio-bar-inner" :style="{width: audioProgress + '%'}"></view>
        </view>
        <text class="audio-time">{{ audioCurrentTime }}/{{ audioDuration }}</text>
      </view>

      <!-- 录音动画 -->
      <view v-if="recording" class="recording-anim">
        <i class="iconfont icon-mic mic-anim"></i>
        <text class="recording-text">正在录音...</text>
      </view>

      <!-- 控制按钮区域 -->
      <view class="control-buttons">
        <button 
          v-if="!interviewing" 
          @click="startInterview" 
          class="primary-button animate-btn"
        >
          开始面试
        </button>
        <template v-else>
          <button 
            @click="nextQuestion" 
            class="primary-button animate-btn"
            :disabled="!canNext"
          >
            下一题
          </button>
          <button 
            @click="endInterview" 
            class="secondary-button animate-btn"
            style="margin-top: 12px;"
          >
            结束面试
          </button>
        </template>
      </view>

      <!-- 新增抽屉组件 -->
      <uni-drawer 
        ref="drawer" 
        mode="left" 
        :mask-click="false"
        :visible="showDrawer"
        class="analysis-drawer"
        width="400"
      >
        <view class="drawer-content">
          <view class="drawer-header">
            <text class="drawer-title">面试分析报告</text>
            <i class="iconfont icon-close" @click="showDrawer = false"></i>
          </view>
          <view ref="chartContainer" id="chartContainer" class="chart-container">

          </view>

          <view class="charts-box">
          <view class="analysis-section">
            <text class="section-title">表情分析</text>
            <text class="section-content">{{ analysisResult }}</text>
          </view>
          
          <view class="analysis-section">
            <text class="section-title">回答分析</text>
            <text class="section-content">{{ userAnalysisResult }}</text>
          </view>
          
          <view class="analysis-section">
            <text class="section-title">总结分析</text>
            <text class="section-content">{{ totalAnalysisResult }}</text>
          </view>
          </view>
        </view>
      </uni-drawer>

      <!-- 分析结果展示 -->
      <view class="analysis-result" v-if="showAnalysis">
        <text class="result-title"><i class="iconfont icon-analysis"></i> 面试分析：</text>
        <text class="result-content">{{ analysisResult }}</text>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>

import { createVoiceAPI, expressionAnalysisResultAPI } from '@/service/interview'
import type { expressionResponse, FileDetail } from '@/types/interview'
import { BaseRequestUrl } from '@/utils/properties'
import { onLoad } from '@dcloudio/uni-app'
import { ref, nextTick, computed, getCurrentInstance } from 'vue'
// import * as echarts from 'echarts'


const interviewing = ref(false)
let intervalId: number | null = null
let recorderManager: UniApp.RecorderManager | null = null
const cameraRef = ref<any>(null)
const cameraContext = uni.createCameraContext()
const fileData = ref<FileDetail[]>([])
// 表情分析结果
const analysisResult = ref<string>("")
//用户答案分析结果
const userAnalysisResult = ref<string>("")
//总体分析结果
const totalAnalysisResult = ref<string>("")
const audioData = ref<string[]>([])
const showAnalysis = ref(true)
const canNext = ref(false)
let waitingForNext = false
const chart = ref<any>(null)
const query = defineProps<{
  questions: string[]
}>()

const initChart = () => {
//  const chartContainer = document.getElementById('chartContainer')
//   chart.value = echarts.init(chartContainer)
//   chart.value.setOption(
//     {
//   title: {
//     text: 'Basic Radar Chart'
//   },
//   legend: {
//     data: ['Allocated Budget', 'Actual Spending']
//   },
//   radar: {
//     // shape: 'circle',
//     indicator: [
//       { name: 'Sales', max: 6500 },
//       { name: 'Administration', max: 16000 },
//       { name: 'Information Technology', max: 30000 },
//       { name: 'Customer Support', max: 38000 },
//       { name: 'Development', max: 52000 },
//       { name: 'Marketing', max: 25000 }
//     ]
//   },
//   series: [
//     {
//       name: 'Budget vs spending',
//       type: 'radar',
//       data: [
//         {
//           value: [4200, 3000, 20000, 35000, 50000, 18000],
//           name: 'Allocated Budget'
//         },
//         {
//           value: [5000, 14000, 28000, 26000, 42000, 21000],
//           name: 'Actual Spending'
//         }
//       ]
//     }
//   ]
// }
//   )
}


onLoad(async () => {
  initChart()
  
  // 安全解析URL参数
  try {
    const questionsParam = query.questions
    const questionsList = questionsParam ? JSON.parse(JSON.stringify(questionsParam)) : []
    
    console.log("当前props的问题信息为", questionsList)
    questionsList.forEach((item: string) => {
      questions.value.push({ text: item, audioUrl: "" })
    })
  } catch (error) {
    console.error("解析问题参数失败:", error)
    uni.showToast({
      title: '加载问题失败',
      icon: 'none'
    })
    return
  }
  
  console.log("当前questions数据为",questions.value)
  //提取问题内容的字符串列表
  const questionTexts = questions.value.map(q => q.text)
  const res = await createVoiceAPI(questionTexts)
  const audioUrlsResult = res.data
  //将音频地址赋值给对应的题目
  questions.value.forEach((q, index) => {
    q.audioUrl = audioUrlsResult[index] || ""
  })
  console.log("最终生成的结果为",audioUrlsResult)
})

// 题目数据结构调整，增加audioUrl
const questions = ref<{ text: string, audioUrl: string }[]>([
])
const currentQuestionIndex = ref(0)
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])

// 音频播放与录音状态
const audioPlaying = ref(false)
const audioProgress = ref(0)
const audioCurrentTime = ref('00:00')
const audioDuration = ref('00:00')
let audioTimer: any = null
let innerAudioContext: UniApp.InnerAudioContext | null = null
const recording = ref(false)


// 播放题目音频
const playQuestionAudio = () => {
  if (audioPlaying.value || recording.value) return
  canNext.value = false
  audioPlaying.value = true
  audioProgress.value = 0
  audioCurrentTime.value = '00:00'
  audioDuration.value = '00:00'
  if (innerAudioContext) {
    innerAudioContext.destroy()
    innerAudioContext = null
  }
  innerAudioContext = uni.createInnerAudioContext()
  innerAudioContext.src = currentQuestion.value.audioUrl
  innerAudioContext.obeyMuteSwitch = false
  console.log("当前音频地址", currentQuestion.value.audioUrl)
  innerAudioContext.onPlay(() => {
    console.log('开始播放音频')
    // 获取音频总时长
    audioTimer = setInterval(() => {
      if (innerAudioContext) {
        const cur = innerAudioContext.currentTime || 0
        const dur = innerAudioContext.duration || 1
        audioProgress.value = Math.min(100, Math.floor((cur / dur) * 100))
        audioCurrentTime.value = formatTime(cur)
        audioDuration.value = formatTime(dur)
      }
    }, 200)
  })
  innerAudioContext.onEnded(() => {
    canNext.value = true
    audioPlaying.value = false
    clearInterval(audioTimer)
    audioProgress.value = 100
    audioCurrentTime.value = audioDuration.value
    startRecording()
  })
  innerAudioContext.onError(() => {
    audioPlaying.value = false
    clearInterval(audioTimer)
    uni.showToast({ title: '音频播放失败', icon: 'none' })
  })
  innerAudioContext.play()
}

function formatTime(sec: number) {
  const m = Math.floor(sec / 60)
  const s = Math.floor(sec % 60)
  return `${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`
}

// 录音逻辑
const startRecording = () => {
  if (recording.value) return
  recording.value = true
  canNext.value = false
  if (!recorderManager) {
    recorderManager = uni.getRecorderManager()
  }
  recorderManager.onStart(() => {
    console.log('录音开始')
    canNext.value = true
  })
  recorderManager.onStop((res) => {
    recording.value = false
    
    uni.uploadFile({
      url: BaseRequestUrl + '/server-ai/interview/audioAnalysis',
      filePath: res.tempFilePath,
      name: 'file',
      header: { "Authorization": uni.getStorageSync('Authorization') },
      success: (uploadRes) => {
        audioData.value.push(uploadRes.data)
      }
    })
    if (waitingForNext) {
      waitingForNext = false
      goToNextQuestion()
    }
  })
  recorderManager.start({
    format: 'mp3',
    duration: 15000, // 15秒
    sampleRate: 16000
  })
}

const startInterview = async () => {
  interviewing.value = true
  currentQuestionIndex.value = 0
  fileData.value = []
  audioData.value = []
  analysisResult.value = ''
  
  // 初始化录音管理器（只设置一次）
  recorderManager = uni.getRecorderManager()
  
  // 开始第一题
  playQuestionAudio()
  
  // 拍照逻辑保持不变
  intervalId = setInterval(() => {
    cameraContext.takePhoto({
      quality: 'low',
      success: (res) => {
        uni.uploadFile({
          url: BaseRequestUrl + "/server-ai/interview/expressionAnalysis",
          filePath: res.tempImagePath,
          name: 'file',
          header: { "Authorization": uni.getStorageSync('Authorization') },
          success: (uploadRes) => {
            let data: expressionResponse = JSON.parse(uploadRes.data)
            fileData.value.push(data.data.fileList[0])
          }
        })
      }
    })
  }, 5000)
}

const nextQuestion = async () => {
  if (recording.value && recorderManager) {
    waitingForNext = true
    recorderManager.stop()
    return
  }
  goToNextQuestion()
}

const goToNextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
    canNext.value = false
    playQuestionAudio()
  } else {
    endInterview()
  }
}

const showDrawer = ref(true)
const drawer = ref<any>(null)

const endInterview = async () => {
  drawer.value.open()
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
  if (recorderManager && recording.value) {
    recorderManager.stop()
    recorderManager = null
  }
  interviewing.value = false
  
  // 更新分析结果
  analysisResult.value = '正在分析表情...'
  userAnalysisResult.value = '正在分析回答...'
  totalAnalysisResult.value = '正在生成总结...'
  
  // 获取分析数据
  const res = await expressionAnalysisResultAPI(fileData.value)
  analysisResult.value = res.data
  // 这里需要添加获取回答分析和总结分析的API调用
  
  // 显示抽屉
  showDrawer.value = true
  
}
</script>

<style scoped>
.container {
  position: relative;
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background: #fff;
}
.bg-gradient {
  position: absolute;
  z-index: 0;
  width: 100vw;
  height: 100vh;
  left: 0; top: 0;
  background: #fff;
  opacity: 1;
}
.camera-preview {
  align-self: flex-end;
  margin: 24px 24px 0 0;
  z-index: 2;
}
.interview-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 2;
  margin-top: 0;
  justify-content: center;
}
.question-title-center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120px;
  margin-bottom: 18px;
}
.question-text {
  font-size: 26px;
  color: #2563eb;
  font-weight: 700;
  letter-spacing: 1px;
  display: block;
  text-shadow: 0 2px 8px #e3eaf6;
}
.audio-progress-bar {
  margin: 0 auto 18px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}
.audio-bar {
  width: 120px;
  height: 8px;
  background: #e5e7eb;
  border-radius: 4px;
  overflow: hidden;
}
.audio-bar-inner {
  height: 100%;
  background: #2563eb;
  border-radius: 4px;
  transition: width 0.2s;
}
.audio-time {
  font-size: 12px;
  color: #7a8ba3;
}
.recording-anim {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 18px 0 0 0;
  animation: fadeIn 0.5s;
}
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
.icon-mic {
  font-size: 32px;
  color: #2563eb;
  margin-right: 10px;
  animation: micFlash 1s infinite alternate;
}
@keyframes micFlash {
  0% { filter: brightness(1); }
  100% { filter: brightness(1.3); }
}
.recording-text {
  font-size: 18px;
  color: #2563eb;
  font-weight: bold;
}
.control-buttons {
  margin-top: auto;
  margin-bottom: 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 18px;
}
.primary-button, .secondary-button {
  min-width: 180px;
  font-size: 18px;
  border-radius: 24px;
  padding: 14px 0;
  font-weight: bold;
  box-shadow: 0 2px 12px rgba(37,99,235,0.06);
  transition: box-shadow 0.2s, transform 0.2s, background 0.2s, color 0.2s;
}
.primary-button {
  background: #fff;
  color: #2563eb;
  border: 2px solid #2563eb;
}
.primary-button:active {
  background: #2563eb;
  color: #fff;
}
.primary-button:disabled {
  background: #f3f4f6;
  color: #b6c6e3;
  border-color: #e5e7eb;
}
.secondary-button {
  background: #fff;
  color: #2563eb;
  border: 2px solid #2563eb;
}
.secondary-button:active {
  background: #2563eb;
  color: #fff;
}
.analysis-result {
  background: #f8fafc;
  border-radius: 16px;
  padding: 20px 24px;
  margin: 24px auto 0 auto;
  max-width: 480px;
  box-shadow: 0 4px 24px rgba(37,99,235,0.06);
  text-align: left;
  position: relative;
  z-index: 2;
}
.result-title {
  font-weight: bold;
  color: #2563eb;
  font-size: 18px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.result-content {
  color: #666;
  line-height: 1.7;
  font-size: 16px;
  margin-top: 6px;
}
.animate-btn {
  animation: btnPop 0.4s;
}
@keyframes btnPop {
  0% { transform: scale(0.8); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
.animate-pop {
  animation: popIn 0.5s cubic-bezier(.68,-0.55,.27,1.55);
}
.interview-notice {
  background: #f8fafc;
  border-radius: 16px;
  padding: 20px;
  margin: 0 auto 24px;
  max-width: 480px;
  box-shadow: 0 4px 24px rgba(37,99,235,0.06);
}

.notice-title {
  font-size: 20px;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 16px;
  display: block;
  text-align: center;
}

.notice-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 16px;
  color: #666;
}

.notice-item .iconfont {
  color: #2563eb;
  margin-right: 8px;
  font-size: 18px;
}
/* 新增抽屉样式 */
.analysis-drawer {
  z-index: 999;
}

.drawer-content {
  padding: 24px;
  height: 100%;
  width: 80%;
  display: flex;
  flex-direction: column;
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.drawer-title {
  font-size: 20px;
  font-weight: bold;
  color: #2563eb;
}

.analysis-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #2563eb;
  margin-bottom: 8px;
  display: block;
}

.section-content {
  color: #666;
  line-height: 1.6;
  font-size: 16px;
}

.icon-close {
  font-size: 20px;
  color: #999;
  padding: 8px;
}

.charts-box {
    width: 100%;
    height: 300rpx;
  }

</style>
